﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using InformationSystem.BLL.Core.Service;
using InformationSystem.BLL.Core.Model;
using System.Text;
using InformationSystem.WebSite.Utility;

namespace InformationSystem.WebSite.Forum
{
    public partial class ForumContent : BasePage
    {
        public IForumService ForumService { get; set; }
        protected void Page_Load(object sender, EventArgs e)
        {
            int threadid = 0;
            int requestpage = 1;
            int parentpageid = 1;
            int tabid = 0;
            if (Request.QueryString["threadid"] != null)
            {
                int.TryParse(Request.QueryString["threadid"], out threadid);
            }
            if (Request.QueryString["page"] != null)
            {
                int.TryParse(Request.QueryString["page"], out requestpage);
            }
            if (Request.QueryString["fp"] != null)
            {
                int.TryParse(Request.QueryString["fp"], out parentpageid);
            }
            if (Request.QueryString["tabid"] != null)
            {
                int.TryParse(Request.QueryString["tabid"], out tabid);
            }
            if (requestpage < 1) requestpage = 1;
            if (IsPostBack)
            {
                int sobjtype = -1;
                int sobjid = 0;
                int.TryParse(objtype.Value, out sobjtype);
                int.TryParse(objid.Value, out sobjid);
                if ((sobjtype == 0 || sobjtype == 1) && sobjid != 0)
                {
                    //Do delete logic
                    if (sobjtype == 0)
                    {
                        int forumid = this.DeleteThread(sobjid);
                        if (forumid != 0)
                            Response.Redirect(string.Format("ForumList.aspx?forumid={0}&page={1}&tabid={2}", forumid, parentpageid, tabid), true);
                        else
                            Response.Redirect(string.Format("ForumContent.aspx?threadid={0}&page={1}", threadid, requestpage), true);
                    }
                    else
                    {
                        int pageid = this.DeleteThreadReply(threadid, sobjid, requestpage);
                        if (pageid == -1)
                        {
                            pageid = requestpage;
                        }
                        else if (pageid == 0)
                        {
                            pageid = 1;
                        }
                        Response.Redirect(string.Format("ForumContent.aspx?threadid={0}&page={1}", threadid, pageid), true);

                    }
                    return;
                }
                //Do Save Logic
                string content = StringCheck.GetSafeContent(brand.Text.Trim());
                bool isanoreply = anoreply.Checked;
                bool gotolast = !fastpostrefresh.Checked;
                if (content.Trim() == string.Empty) return;
                this.saveThreadReply(threadid, content, isanoreply, gotolast);
            }
            else
            {
                //read thread
                this.ReadThread(threadid, requestpage);
            }

        }

        private int DeleteThread(int threadid)
        {
            int forumid = 0;
            bool result = ForumService.DeleteThread(threadid, LoginUser, out forumid);
            if (result)
            {
                return forumid;
            }
            else
            {
                return 0;
            }
        }
        private int DeleteThreadReply(int threadid, int replyid, int pageid)
        {
            if (!ForumService.DeleteReply(replyid, LoginUser)) return -1;
            int totalreplyscount = ForumService.GetThreadReplysCount(threadid);
            int pagerecord = (int)Application[Common.ForumReplyCount];
            int pagesneed = totalreplyscount / pagerecord + (totalreplyscount % pagerecord == 0 ? 0 : 1);
            return pageid > pagesneed ? pagesneed : pageid;
        }
        private void ReadThread(int threadid, int requestpage)
        {
            ThreadInfo tinfo = ForumService.GetThreadDetail(threadid, base.LoginUser);
            IList<ThreadReplyInfo> replylist = null;
            int totalrecords = 0;
            int pagesize = (int)Application[Common.ForumReplyCount];
            if (tinfo == null) return; //重定向
            newspecialend.HRef = "NewThread.aspx?forumid=" + tinfo.CollegeID.ToString();
            newspecialtop.HRef = "NewThread.aspx?forumid=" + tinfo.CollegeID.ToString();
            threaduri.HRef = "ForumContent.aspx?threadid=" + tinfo.ThreadID.ToString();
            threaduri.InnerText = tinfo.ThreadSubject;
            thread_subject.InnerText = tinfo.ThreadSubject;
            thread_subject.HRef = "ForumContent.aspx?threadid=" + tinfo.ThreadID.ToString();
            lbanoreply.Visible = tinfo.CanReplyHideName;
            fastpostform.Visible = tinfo.CanReply;
            StringBuilder builder = new StringBuilder();
            if (requestpage == 1)
            {
                divtotal.Visible = true;
                divfloor.Visible = false;
                viewcount.InnerText = tinfo.VisitedCount.ToString();
                replycount.InnerText = tinfo.ReplyCount.ToString();
                replylist = ForumService.GetThreadReplyInfo(tinfo.ThreadID, pagesize, requestpage, out totalrecords);
                builder.Append(this.RenderTopic(tinfo));
            }
            else
            {
                divtotal.Visible = false;
                divfloor.Visible = true;
                divfloor.InnerHtml = string.Format("楼主: <a title=\"{0}\" href=\"javascript:void(0)\">{0}</a>", (tinfo.HideName && tinfo.CreatUserID != LoginUser.UserID) ? Common.Anonymous : tinfo.CreatUserName);
                replylist = ForumService.GetThreadReplyInfo(tinfo.ThreadID, pagesize, requestpage, out totalrecords);
            }
            //计算主题在内
            //totalrecords++;
            foreach (var item in replylist)
            {
                builder.Append(this.RenderReply(tinfo, item));
            }
            post.InnerHtml = builder.ToString();
            //生成分页链接
            this.RenderPageNo(requestpage, totalrecords, tinfo.ThreadID);
            //update view count
            ForumService.UpdateReadCount(tinfo.ThreadID);
        }

        private void RenderPageNo(int requestpage, int allrecordscount, int threadid)
        {
            int pagerecord = (int)Application[Common.ForumReplyCount];
            int pagesneed = allrecordscount / pagerecord + (allrecordscount % pagerecord == 0 ? 0 : 1);
            StringBuilder innerhtml = new StringBuilder();
            if (requestpage > pagesneed) requestpage = pagesneed;
            if (pagesneed < 11)
            {
                for (int i = 1; i < pagesneed + 1; i++)
                {
                    if (requestpage == i)
                    {
                        innerhtml.AppendFormat("<strong>{0}</strong>", i);
                    }
                    else
                    {
                        innerhtml.AppendFormat("<a href='{0}'>{1}</a>", string.Format("ForumContent.aspx?threadid={0}&page={1}", threadid, i), i);
                    }
                }
            }
            else
            {
                if (requestpage < 6)
                {
                    for (int i = 1; i < 6; i++)
                    {
                        if (requestpage == i)
                        {
                            innerhtml.AppendFormat("<strong>{0}</strong>", i);
                        }
                        else
                        {
                            innerhtml.AppendFormat("<a href='{0}'>{1}</a>", string.Format("ForumContent.aspx?threadid={0}&page={1}", threadid, i), i);
                        }
                    }

                    if (pagesneed - 5 < 5)
                    {
                        for (int i = 6; i < pagesneed + 1; i++)
                        {
                            innerhtml.AppendFormat("<a href='{0}'>{1}</a>", string.Format("ForumContent.aspx?threadid={0}&page={1}", threadid, i), i);
                        }
                    }
                    else
                    {
                        for (int i = 6; i < 10; i++)
                        {
                            innerhtml.AppendFormat("<a href='{0}'>{1}</a>", string.Format("ForumContent.aspx?threadid={0}&page={1}", threadid, i), i);
                        }
                        innerhtml.AppendFormat("<a href='{0}'>...{1}</a>", string.Format("ForumContent.aspx?threadid={0}&page={1}", threadid, pagesneed), pagesneed);
                    }
                }
                if (requestpage > 5)
                {
                    innerhtml.AppendFormat("<a href='{0}'>1...</a>", string.Format("ForumContent.aspx?threadid={0}&page={1}", threadid, 1));
                    for (int i = requestpage - 3; i < requestpage; i++)
                    {
                        innerhtml.AppendFormat("<a href='{0}'>{1}</a>", string.Format("ForumContent.aspx?threadid={0}&page={1}", threadid, i), i);
                    }
                    innerhtml.AppendFormat("<strong>{0}</strong>", requestpage);

                    if (pagesneed - requestpage < 5)
                    {
                        for (int i = requestpage + 1; i < pagesneed + 1; i++)
                        {
                            innerhtml.AppendFormat("<a href='{0}'>{1}</a>", string.Format("ForumContent.aspx?threadid={0}&page={1}", threadid, i), i);
                        }
                    }
                    else
                    {
                        for (int i = requestpage + 1; i < requestpage + 4; i++)
                        {
                            innerhtml.AppendFormat("<a href='{0}'>{1}</a>", string.Format("ForumContent.aspx?threadid={0}&page={1}", threadid, i), i);
                        }
                        innerhtml.AppendFormat("<a href='{0}'>...{1}</a>", string.Format("ForumContent.aspx?threadid={0}&page={1}", threadid, pagesneed), pagesneed);
                    }
                }
                innerhtml.AppendFormat("<label><input type='text' name='custompage' class='px' size='2' title='输入页码，按回车快速跳转' value='1' onkeydown=\"if(event.keyCode==13) {0}window.location='ForumContent?threadid={1}&page='+this.value; {2}\" /><span title='共 {3} 页'> / {4} 页</span></label>", "{", threadid, "}", pagesneed);
            }
            fastpagetop.InnerHtml = innerhtml.ToString();
            fastpagebottom.InnerHtml = innerhtml.ToString();
        }

        private string RenderTopic(ThreadInfo tinfo)
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat("<div id=\"post_{0}\">", tinfo.ThreadID);
            builder.Append("<table cellspacing=\"0\" cellpadding=\"0\">");
            builder.Append("<tr>");
            builder.AppendFormat("<td class=\"pls\" rowspan=\"2\"><div class=\"pi\"><div class=\"authi\"><strong>{0}</strong></div></div><div><p class=\"xg1\">{1}</p></div></td>", (tinfo.HideName && tinfo.CreatUserID != LoginUser.UserID) ? Common.Anonymous : tinfo.CreatUserID, (tinfo.HideName && tinfo.CreatUserID != LoginUser.UserID) ? Common.Anonymous : tinfo.CreatUserName);
            builder.AppendFormat("<td class=\"plc\"><div class=\"pi\"><div class=\"pti\"><div class=\"authi\"><em>发表于 {0}</em> <span class=\"pipe\">|</span> </div> </div></div><div class=\"pct\"><div class=\"t_fsz\"><table cellspacing=\"0\" cellpadding=\"0\"><tr><td class=\"t_f\">{1}<br /></td></tr></table></div></div></td>", tinfo.CreateTime, tinfo.Content);
            builder.Append("<tr><td class=\"plc plm\"></td></tr>");
            builder.AppendFormat("<tr><td class=\"pls\"></td><td class=\"plc\"><div class=\"po\"><div class=\"pob cl\"><p>{0}</p></div></div></td></tr>", (tinfo.CreatUserID == base.LoginUser.UserID || tinfo.CollegeID == LoginUser.CollegeID && LoginUser.LoginUserType == UserType.Assistant) ? ("<a href=\"javascript:void(0)\" onclick=\"deleteinfo('thread'," + tinfo.ThreadID.ToString() + ")\">删除</a>") : "");
            builder.Append("<tr class=\"ad\"> <td class=\"pls\"></td><td class=\"plc\"></td> </tr>");
            builder.Append(" </table> </div>");
            return builder.ToString();
        }

        private string RenderReply(ThreadInfo tinfo, ThreadReplyInfo reply)
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat("<div id=\"post_{0}\">", reply.ForumReplyID);
            builder.Append("<table cellspacing=\"0\" cellpadding=\"0\">");
            builder.Append("<tr>");
            builder.AppendFormat("<td class=\"pls\" rowspan=\"2\"><div class=\"pi\"><div class=\"authi\"><strong>{0}</strong></div></div><div><p class=\"xg1\">{1}</p></div></td>", (reply.HideName && reply.ReplyUserID != LoginUser.UserID) ? Common.Anonymous : reply.ReplyUserID, (reply.HideName && reply.ReplyUserID != LoginUser.UserID) ? Common.Anonymous : reply.ReplyUserName);
            builder.AppendFormat("<td class=\"plc\"><div class=\"pi\"><div class=\"pti\"><div class=\"authi\"><em>发表于 {0}</em> <span class=\"pipe\">|</span> </div> </div></div><div class=\"pct\"><div class=\"t_fsz\"><table cellspacing=\"0\" cellpadding=\"0\"><tr><td class=\"t_f\">{1}<br /></td></tr></table></div></div></td>", reply.ReplyTime, reply.Content);
            builder.Append("<tr><td class=\"plc plm\"></td></tr>");
            builder.AppendFormat("<tr><td class=\"pls\"></td><td class=\"plc\"><div class=\"po\"><div class=\"pob cl\"><p>{0}</p></div></div></td></tr>", (reply.ReplyUserID == base.LoginUser.UserID || tinfo.CreatUserID == LoginUser.UserID || tinfo.CollegeID == LoginUser.CollegeID && LoginUser.LoginUserType == UserType.Assistant) ? ("<a href=\"javascript:void(0)\" onclick=\"deleteinfo('reply'," + reply.ForumReplyID.ToString() + ")\">删除</a>") : "");
            builder.Append("<tr class=\"ad\"> <td class=\"pls\"></td><td class=\"plc\"></td> </tr>");
            builder.Append(" </table> </div>");
            return builder.ToString();
        }
        private void saveThreadReply(int threadid, string content, bool isanoreply, bool gotolast)
        {
            ThreadReplyInfo rinfo = new ThreadReplyInfo();
            rinfo.Content = content;
            rinfo.HideName = isanoreply;
            rinfo.ReplyTime = DateTime.Now;
            rinfo.ReplyUserID = LoginUser.UserID;
            rinfo.ReplyUserName = LoginUser.UserName;
            rinfo.ThreadID = threadid;
            if (ForumService.CreateReply(threadid, rinfo, LoginUser))
            {
                if (gotolast)
                {
                    int totalreplyscount = ForumService.GetThreadReplysCount(threadid);
                    int pagerecord = (int)Application[Common.ForumReplyCount];
                    int pagesneed = totalreplyscount / pagerecord + (totalreplyscount % pagerecord == 0 ? 0 : 1);

                    Response.Redirect(string.Format("ForumContent.aspx?threadid={0}&page={1}", threadid, pagesneed), true);
                }
                else
                {
                    Response.Redirect(string.Format("ForumContent.aspx?threadid={0}&page={1}", threadid, 1), true);
                }
            }
        }

        protected override bool CommitPermissionCheck()
        {
            throw new NotImplementedException();
        }
    }
}